// src/components/CellComponent.js
import React, { memo, useRef, useEffect, useCallback } from 'react';
import { Input, Tooltip } from 'antd';
import { CommentOutlined, ExpandAltOutlined } from '@ant-design/icons';

// 判断是否为HTML内容的工具函数
function isHTML(str) {
  return typeof str === 'string' && /<[^>]+>/.test(str);
}

// 单元格内容组件 - 使用React.memo优化
const CellContent = memo(({ 
  cellData, 
  rowIndex, 
  columnName, 
  isEditing, 
  cellAnnotations,
  onCellEdit,
  onExpandClick,
  onEditingCancel 
}) => {
  // 使用useRef来持久化提交状态，避免重复提交
  const isSubmittingRef = useRef(false);
  const inputRef = useRef(null);

  // 重置提交状态的useEffect
  useEffect(() => {
    if (!isEditing) {
      isSubmittingRef.current = false;
    }
  }, [isEditing]);

  // 处理提交的回调函数
  const handleSubmit = useCallback(() => {
    if (isSubmittingRef.current || !inputRef.current) return;
    
    isSubmittingRef.current = true;
    const newValue = inputRef.current.input.value;
    onCellEdit(rowIndex, columnName, newValue);
    
    // 延迟重置提交状态
    setTimeout(() => {
      isSubmittingRef.current = false;
    }, 100);
  }, [rowIndex, columnName, onCellEdit]);

  if (!cellData) return '';

  const { value } = cellData;
  
  // 计算单元格样式
  let cellStyle = {};
  const highlightAnnotation = cellAnnotations.find(
    ann => ann.annotation_type === 'highlight'
  );
  if (highlightAnnotation) {
    const annotationData = JSON.parse(highlightAnnotation.annotation_data);
    cellStyle = {
      backgroundColor: annotationData.backgroundColor,
      color: annotationData.textColor,
    };
  }

  // 编辑模式
  if (isEditing) {
    return (
      <Input
        ref={inputRef}
        defaultValue={value}
        autoFocus
        onPressEnter={handleSubmit}
        onBlur={() => {
          // 使用setTimeout确保onPressEnter先执行
          setTimeout(() => {
            if (!isSubmittingRef.current) {
              handleSubmit();
            }
          }, 10);
        }}
        onKeyDown={(e) => {
          if (e.key === 'Escape') {
            onEditingCancel();
          }
        }}
        style={{
          width: '100%',
          height: '32px',
        }}
      />
    );
  }

  // 显示模式
  const displayValue = typeof value === 'string' ? value : String(value);
  const isLongText = displayValue.length > 50;

  return (
    <div
      style={{
        ...cellStyle,
        position: 'relative',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        width: 200,
        height: 40,
        lineHeight: '40px',
        borderRadius: '4px',
        padding: '0 8px',
        paddingRight: '32px',
      }}
    >
      <span>{displayValue}</span>
      
      {/* 批注指示器 */}
      {cellAnnotations.length > 0 && (
        <Tooltip title={`${cellAnnotations.length} 条批注`}>
          <CommentOutlined 
            style={{ 
              position: 'absolute',
              top: '50%',
              right: '28px',
              transform: 'translateY(-50%)',
              color: '#1890ff',
              fontSize: '12px',
              zIndex: 2,
            }} 
          />
        </Tooltip>
      )}
      
      {/* 放大图标 */}
      <Tooltip title="放大查看">
        <ExpandAltOutlined
          style={{
            position: 'absolute',
            top: '50%',
            right: '8px',
            transform: 'translateY(-50%)',
            fontSize: '12px',
            color: isLongText ? '#1890ff' : '#bfbfbf',
            cursor: 'pointer',
            zIndex: 2,
            opacity: 0.7,
            transition: 'all 0.2s',
          }}
          onClick={(e) => {
            e.stopPropagation();
            onExpandClick(cellData, rowIndex, columnName);
          }}
          onMouseEnter={(e) => {
            e.target.style.opacity = '1';
            e.target.style.color = '#1890ff';
          }}
          onMouseLeave={(e) => {
            e.target.style.opacity = '0.7';
            e.target.style.color = isLongText ? '#1890ff' : '#bfbfbf';
          }}
        />
      </Tooltip>
    </div>
  );
});

// 单元格容器组件 - 使用React.memo优化
const CellContainer = memo(({ 
  cellData, 
  rowIndex, 
  columnName, 
  isSelected, 
  isEditing,
  annotations,
  onCellClick,
  onCellDoubleClick,
  onCellEdit,
  onExpandClick,
  onEditingCancel
}) => {
  const cellKey = `${rowIndex}-${columnName}`;
  const cellAnnotations = annotations[cellKey] || [];

  // 使用useCallback缓存点击事件处理函数
  const handleClick = useCallback(() => {
    onCellClick(rowIndex, columnName);
  }, [rowIndex, columnName, onCellClick]);

  const handleDoubleClick = useCallback(() => {
    onCellDoubleClick(rowIndex, columnName);
  }, [rowIndex, columnName, onCellDoubleClick]);

  return (
    <div
      className={`cell-container ${isSelected ? 'selected-cell' : ''}`}
      style={{ 
        minHeight: 32, 
        cursor: 'pointer',
        margin: '-8px -12px',
        padding: '8px 12px',
      }}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
    >
      <CellContent
        cellData={cellData}
        rowIndex={rowIndex}
        columnName={columnName}
        isEditing={isEditing}
        cellAnnotations={cellAnnotations}
        onCellEdit={onCellEdit}
        onExpandClick={onExpandClick}
        onEditingCancel={onEditingCancel}
      />
    </div>
  );
});

// 设置组件显示名称，便于调试
CellContent.displayName = 'CellContent';
CellContainer.displayName = 'CellContainer';

export default CellContainer;